import { 
  GET_LIST_DATA, 
  LEFT_CLICK, 
  ADD_SELECT_ITEM, 
  MIN_SELECT_ITEM,
  SHOW_CHOOSE_CONTENT ,
  CLEAR_CAR
} from '../actions/actionType.js';

// 初始化state
const initState = {
    listData: {},
    currentLeftIndex: 0,
    showChooseContent: false,
    poiInfo: {}
}

const getListData = (state, action) => {
  // console.log(action.obj.data)
  return {...state, poiInfo: action.obj.data, listData: action.obj.data}
}

const itemClick = (state, action) => {
  return {...state, currentLeftIndex: action.obj.currentLeftIndex}
}

const addSelectItem = (state, action) => {
  return delSelectItem(state, action, ADD_SELECT_ITEM)
  // let listData = state.listData
  // let list = this.props.listData.food_spu_tags || []
  // let currentItem = list[state.currentLeftIndex]
  // currentItem.spus[action.obj.index].chooseCount++
  // let _listData = JSON.parse(JSON.stringify(listData))
  // return {...state, listData: _listData}
}

const minSelectItem = (state, action) => {
  return delSelectItem(state, action, MIN_SELECT_ITEM)
}

const chooseContent = (state, action) => {
  return {...state, showChooseContent: action.obj.flag}
}

const delSelectItem = (state, action, type) => {
  let listData = state.listData
  let list = listData.food_spu_tags || []
  let currentItem = list[action.outIndex || state.currentLeftIndex]
  
  if(type === ADD_SELECT_ITEM){
    currentItem.spus[action.obj.index].chooseCount++
  }else{
    currentItem.spus[action.obj.index].chooseCount--
  }
  
  let _listData = JSON.parse(JSON.stringify(listData))
  return {...state, listData: _listData}
}

const clearCar = (state) => {
  let listData = state.listData
  let list = listData.food_spu_tags || []

  for(let i = 0; i < list.length; i++){
    let spus = list[i].spus || []
    for(let j = 0; j < spus.length; j++){
      spus[j].chooseCount = 0
    }
  }
  return {...state, listData: JSON.parse(JSON.stringify(listData))}
}

const menuReducer = (state = initState, action) => {
    switch(action.type) {
        case GET_LIST_DATA: 
          return getListData(state, action);
        case LEFT_CLICK:
          return itemClick(state, action)
        case ADD_SELECT_ITEM:
          return addSelectItem(state, action)
        case MIN_SELECT_ITEM:
          return minSelectItem(state, action)
        case SHOW_CHOOSE_CONTENT:
          return chooseContent(state, action)
        case CLEAR_CAR:
          return clearCar(state, action)
        default: 
          return state;
    }
}

export default menuReducer;